/*
 * @Author: NtyAaron
 * @Date: 2021-04-12 11:13:45
 * @LastEditors: NtyAaron
 * @LastEditTime: 2021-05-31 17:35:25
 * @Description: file content
 * @FilePath: \miniapp\dwq\pages\health\health.js
 */
import {
  getCity,
  getDefCity,
  getLangCityName,
  getLangProvinceName,
} from '../../utils/cityJson'
import { formatTime } from '../../utils/util.js'
import { _t } from '../../i18n/base'
import {
  getDomesticInfo,
  getCitys,
  getCityId,
  getNationwideEpidemic,
  getOrganization,
  getPolicy,
} from '../../api/health/health'
Page({
  data: {
    active: 0,
    domesticData: {},
    travelInfo: {},
    organizationCityShow: false,
    policyCityShow: false,
    startCityText: '',
    endCityText: '',
    province: '广东',
    city: '',
    type: 1,
    language: 1,
    datas: [],
    organizationList: [],
    inputValue: '',
    organizationStatus: false,
    cityParse: {},
    citys: {},
    descData: {
      pubTime: '',
      pubDateStr: '',
      lang: [],
    },
    epidemicStatistics: [
      {
        name: '本土现存确诊',
        desc: 'currentConfirmedCount',
        comparisonDesc: 'currentConfirmedIncr',
        backgroundColor: '#FFFAF7',
        fontColor: '#E57632',
      },
      {
        name: '累计确诊',
        desc: 'confirmedCount',
        comparisonDesc: 'confirmedIncr',
        backgroundColor: '#FFF8F8',
        fontColor: '#E57632',
      },
      {
        name: '累计境外输入',
        desc: 'suspectedCount',
        comparisonDesc: 'suspectedIncr',
        backgroundColor: '#FFF4F4',
        fontColor: '#B0372C',
      },
      {
        name: '累计治愈',
        desc: 'curedCount',
        comparisonDesc: 'curedIncr',
        backgroundColor: '#FEF7FF',
        fontColor: '#9F4AB1',
      },
      {
        name: '累计死亡',
        desc: 'deadCount',
        comparisonDesc: 'deadIncr',
        backgroundColor: '#F1F5FF',
        fontColor: '#6184E8',
      },
      {
        name: '现存无症状',
        desc: 'seriousCount',
        comparisonDesc: 'seriousIncr',
        backgroundColor: '#F3F6F8',
        fontColor: '#5A6066',
      },
    ],
    overseasEpidemicStatistics: [
      {
        name: '现存确诊',
        desc: 'currentConfirmedCount',
        comparisonDesc: 'currentConfirmedIncr',
        backgroundColor: '#FFFAF7',
        fontColor: '#E57632',
        descBackgroundColor: '#FFEFE6',
      },
      {
        name: '累计确诊',
        desc: 'confirmedCount',
        comparisonDesc: 'confirmedIncr',
        backgroundColor: '#FFF8F8',
        fontColor: '#E61C1D',
        descBackgroundColor: '#FFDFDF',
      },
      {
        name: '累计治愈',
        desc: 'curedCount',
        comparisonDesc: 'curedIncr',
        backgroundColor: '#F1F5FF',
        fontColor: '#6184E8',
        descBackgroundColor: '#DDE6FF',
      },
      {
        name: '累计死亡',
        desc: 'deadCount',
        comparisonDesc: 'deadIncr',
        backgroundColor: '#F3F6F8',
        fontColor: '#5A6066',
        descBackgroundColor: '#DCDCDC',
      },
    ],
    columnsCity: [],
    policyCityList: [],
    pageLoading: false,
    totalCount: 0,
    collectStatus: 0,
    page: 1,
    size: 10,
    daysAgo: false,
    showTips: false,
  },
  // 出行防疫政策
  async getPolicy() {
    let cityObj = {
      from: '',
      to: '',
    }
    let { result } = await getCitys()
    if (result.length > 0) {
      result.map((item) => {
        item.citys.map((cItem) => {
          if (
            getLangCityName(this.data.startCityText, this.data.language, 1) ==
            cItem.city
          ) {
            cityObj.from = cItem.city_id
          }
          if (
            getLangCityName(this.data.endCityText, this.data.language, 1) ==
            cItem.city
          ) {
            cityObj.to = cItem.city_id
          }
        })
      })
      let { result: res } = await getPolicy(cityObj)
      if (res.f_tag) {
        this.setData({
          travelInfo: res,
        })
      }
    } else {
      wx.showToast({
        title: this.data.lang['没有结果'],
      })
    }
  },
  // 获取城市id
  async getCityId(e) {
    let { result } = await getCityId({ city: e })
    if (result.cityInfo) {
      return result.cityInfo.city_id
    } else {
      this.setData({
        organizationList: [],
        showTips: true,
      })
    }
  },
  // 检测机构列表
  async getOrganization() {
    let cityId = await this.getCityId(
      getLangCityName(this.data.city, this.data.language, 1)
    )
    let info = {
      cityId,
      language: this.data.language,
      page: this.data.page,
      size: this.data.size,
    }
    let { result } = await getOrganization(info)
    if (result.length) {
      if (this.data.language == 3) {
        this.setData({
          organizationList: this.data.organizationList.concat(result),
        })
      } else {
        this.setData({
          showTips: false,
          organizationList: result,
        })
      }
    } else {
      this.setData({
        showTips: true,
        organizationList: [],
      })
    }
  },
  // 国内疫情数据
  async getDomesticInfo() {
    let { result } = await getDomesticInfo()
    this.setData({
      domesticData: result[0].desc,
    })
    let news = result[0].news[0]
    let time = new Date(news.pubDate)
    let index = news.pubDateStr.indexOf('小时前')
    if (index == -1) {
      index = news.pubDateStr.indexOf('天前')
      this.setData({
        daysAgo: true,
      })
    }
    let timeStr = news.pubDateStr.substring(0, index)
    var descData = {
      pubTime: formatTime(time),
      pubDateStr: timeStr,
    }
    this.setData({
      descData,
    })
    let inwardSubstituteList = this.data.epidemicStatistics
    inwardSubstituteList.map((item) => {
      for (let i in this.data.domesticData) {
        if (i == item.desc) {
          item.num = this.data.domesticData[i]
          item.foreign = this.data.domesticData.foreignStatistics[i]
        }
        if (i == item.comparisonDesc) {
          item.comparison = this.data.domesticData[i]
        }
        this.setData({
          epidemicStatistics: inwardSubstituteList,
        })
      }
    })
    let overseasSubstituteList = this.data.overseasEpidemicStatistics
    overseasSubstituteList.map((item, index) => {
      for (let i in this.data.domesticData) {
        if (i == item.desc) {
          item.num = this.data.domesticData[i]
          item.foreign = this.data.domesticData.foreignStatistics[i]
        }
        if (i == item.comparisonDesc) {
          item.comparison = this.data.domesticData[i]
        }
        if (item.name == '累计境外输入' || item.name == '现存无症状') {
          overseasSubstituteList.splice(index, 1)
        }
        this.setData({
          overseasEpidemicStatistics: overseasSubstituteList,
        })
      }
    })
  },
  // 省市区本土病例
  async getNationwideEpidemic() {
    let { result } = await getNationwideEpidemic()
    result.map((item) => {
      item.name = getLangProvinceName(item.name, 1, this.data.language)
    })
    this.setData({
      datas: result,
    })
  },
  // 检测机构分页
  scrollEnd() {
    this.setData({
      page: this.data.page + 1,
      pageLoading: true,
    })
    this.getOrganization()
  },
  // 打开防疫政策城市选择弹窗
  policyCityOpenHandle(e) {
    this.setData({
      type: e.currentTarget.dataset.type,
      policyCityShow: true,
    })
  },
  // 关闭防疫政策城市选择弹窗
  policyCityCloseHandle() {
    this.setData({
      policyCityShow: false,
    })
  },
  // 取消防疫政策城市选择
  policyCityCancelHandle() {
    this.setData({
      policyCityShow: false,
    })
  },
  // 确认防疫政策城市选择
  policyCityConfirmHandle({ detail }) {
    const { value } = detail
    if (this.data.type == '1') {
      if (value[0] == '台湾' || value[0] == '臺灣' || value[0] == 'Taiwan') {
        this.setData({
          startCityText: value[0],
          policyCityShow: false,
        })
      } else {
        this.setData({
          startCityText: value[1],
          policyCityShow: false,
        })
      }
    } else {
      if (value[0] == '台湾' || value[0] == '臺灣' || value[0] == 'Taiwan') {
        this.setData({
          endCityText: value[0],
          policyCityShow: false,
        })
      } else {
        this.setData({
          endCityText: value[1],
          policyCityShow: false,
        })
      }
    }
  },
  // 改变防疫政策城市选择
  policyCityChangeHandle({ detail }) {
    const { picker, value, index } = detail
    picker.setColumnValues(1, this.data.citys[value[0]])
  },
  // 打开检测机构城市选择弹窗
  organizationCityOpenHandle() {
    this.setData({
      organizationCityShow: true,
    })
  },
  // 关闭检测机构城市选择弹窗
  organizationCityCloseHandle() {
    this.setData({
      organizationCityShow: false,
    })
  },
  // 取消检测机构城市选择
  organizationCityCancelHandle() {
    this.setData({
      organizationCityShow: false,
    })
  },
  // 修改检测机构城市选择
  organizationCityChangeHandle({ detail }) {
    const { picker, value, index } = detail
    picker.setColumnValues(1, this.data.cityParse[value[0]])
  },
  // 确认检测机构城市选择
  organizationCityConfirmHandle({ detail }) {
    const { value } = detail
    this.setData({
      province: value[0],
      city: value[1],
      organizationCityShow: false,
    })
    this.getOrganization()
  },
  // 获取检测机构输入内容
  organizationInputKeywordHandle({ detail }) {
    this.setData({
      inputValue: detail.value,
    })
  },
  // 检测机构输入回车事件
  organizationInputSearchHandle() {
    this.getOrganization()
  },
  // 政策复制
  policyCopyHandle({ currentTarget }) {
    let obj = currentTarget.dataset.copy
    let content = obj.high_in_desc + obj.low_in_desc + obj.out_desc
    wx.setClipboardData({
      data: content,
      success: () => {
        wx.showToast({
          title: this.data.lang['复制成功'],
        })
      },
    })
  },
  // 复制防疫政策英文链接
  linkCopyHandle({ currentTarget }) {
    wx.setClipboardData({
      data: currentTarget.dataset.link,
      success: () => {
        wx.showToast({
          title: this.data.lang['复制成功'],
        })
      },
    })
  },
  // 检测机构复制
  orgLinkCopyHandle(e) {
    let type = e.currentTarget.dataset.type
    let HKURL = {
      zh: 'https://www.communitytest.gov.hk/zh-CN/info/',
      tw: 'https://www.communitytest.gov.hk/zh-HK/info/',
      en: 'https://www.communitytest.gov.hk/en/info/',
    }
    let MACURL = {
      zh: 'https://eservice.ssm.gov.mo/rnatestbook/V21/?lang=chs&lab=',
      tw: 'https://eservice.ssm.gov.mo/rnatestbook/V21/',
      en: 'https://eservice.ssm.gov.mo/rnatestbook/V21/?lang=en&lab=',
    }
    let language = wx.getStorageSync('language') //1简体2繁体3英文
    let url = ''
    if (type == 1) {
      url = HKURL[language]
    } else {
      url = MACURL[language]
    }
    wx.setClipboardData({
      data: url,
      success: () => {
        wx.showToast({
          title: this.data.lang['已复制网站网址'],
          icon: 'none',
        })
      },
    })
  },
  // 拨打电话
  makeCallHandle(e) {
    wx.showModal({
      cancelColor: '#F95F22',
      cancelText: this.data.lang['取消'],
      confirmColor: '#999999',
      confirmText: this.data.lang['确定'],
      content: this.data.lang['前往拨打界面'],
      showCancel: true,
      success: (result) => {
        if (result.confirm) {
          wx.makePhoneCall({
            phoneNumber: e.currentTarget.dataset.phone,
          })
        }
      },
    })
  },
  // 设置当前语言
  setLanguage() {
    let lang = _t()
    this.setData({
      lang,
    })
    wx.setNavigationBarTitle({
      title: this.data.lang['健康资讯'],
    })
  },
  // 获取当前语言
  getLanguage() {
    let language = wx.getStorageSync('lang')
    this.setData({
      language,
    })
  },
  // 初始化城市数据
  initCity() {
    const citys = getCity()
    let cityParse = JSON.parse(JSON.stringify(citys))
    delete cityParse['澳门']
    delete cityParse['澳門']
    delete cityParse['香港']
    delete cityParse['台湾']
    delete cityParse['臺灣']
    delete cityParse['Hong Kong']
    delete cityParse['Macao']
    delete cityParse['Taiwan']
    this.setData({
      cityParse,
      citys,
      columnsCity: [
        {
          values: Object.keys(cityParse),
        },
        {
          values: cityParse[getDefCity()],
          defaultIndex: 1,
        },
      ],
      policyCityList: [
        {
          values: Object.keys(citys),
        },
        {
          values: citys[getDefCity()],
          defaultIndex: 1,
        },
      ],
    })
  },
  // 初始化
  onLoad() {
    this.setLanguage()
    this.getLanguage()
    this.initCity()
    this.getDomesticInfo()
    this.getNationwideEpidemic()
  },
})
